package cn.wolfcode.trip.app.web.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.Cmf_Integral;
import cn.wolfcode.trip.base.domain.Sign;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.ICmf_IntegralService;
import cn.wolfcode.trip.base.service.ISignService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/sign")
public class SignController {

    @Autowired
    private ISignService signService;
    @Autowired
    private ICmf_IntegralService integralService;

    //查询当前用户的签到数量
    @GetMapping
    @ResponseBody
    public Object list() {
        Sign sign = signService.list(UserContext.getCurrentUser().getId());
        if (sign != null) {
            /**     1,签到数据的回显是一个数组,参数类型是json格式
             *    所以将数据库中的数据切割后封装成map对象,再储存到
             *    list集合中,所以满足日历回显的数据格式
             *      2,如果当前用户为首次签到,不需回显数据,
             *     此处返回1用于页面的判断
             */
            String[] split = sign.getSignDay().split(",");
            ArrayList<Map<String, Object>> list = new ArrayList<>();
            for (String s : split) {
                Map<String, Object> hashMap = new HashMap<>();
                hashMap.put("signDay", Integer.parseInt(s));
                list.add(hashMap);
            }
            return list;
        }

        return 1;
    }

    //保存签到数据
    @PostMapping(value = "/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Sign sign) {
        sign.setUserId(UserContext.getCurrentUser().getId());
        signService.saveOrUpdate(sign);
        JSONResult result = new JSONResult();
        return result;
    }

    //签到后为当前用户更新积分

    @PostMapping(value = "/updateIntegral")
    @ResponseBody
    public Object updateIntegral(Cmf_Integral integral) {
        JSONResult result = new JSONResult();
        try {
            integral.setUser_id(UserContext.getCurrentUser().getId());
            integralService.saveOrUpdate(integral);
        }catch (Exception e){
            e.printStackTrace();
            result.mark("失败");
        }
        return result;
    }
}
